package com.app.baselibrary.utils

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

/**
 * 线程工具类
 */
object ThreadUtil {

    val uiScope by lazy { CoroutineScope(SupervisorJob() + Dispatchers.Main) }

    val threadScope by lazy { CoroutineScope(SupervisorJob() + Dispatchers.Default) }

    val ioScope by lazy { CoroutineScope(SupervisorJob() + Dispatchers.IO) }


    /**
     * 运行在主线程
     * @param runnable 线程环境切换回调
     * @param delay 延迟执行时间
     */
    @JvmStatic
    @JvmOverloads
    fun runUI(runnable: Runnable, delay: Long = 0){
        threadScope.launch {
            kotlinx.coroutines.delay(delay)
            uiScope.launch {
                runnable.run()
            }
        }
    }


    /**
     * 运行在工作线程，子线程
     * @param runnable 线程环境切换回调
     */
    @JvmStatic
    fun runWorkThread(runnable: Runnable){
        threadScope.launch {
            runnable.run()
        }
    }


    /**
     * 运行在IO线程
     * @param runnable 线程环境切换回调
     */
    @JvmStatic
    fun runIOThread(runnable: Runnable){
        ioScope.launch { runnable.run() }
    }

}